import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_widgets/widgets/animate/mapChart/map_chart.dart';
import 'package:kq_flutter_widgets/widgets/button/kq_bottom_button.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_widgets/widgets/titleBar/kq_title_bar.dart';
import 'package:kq_flutter_widgets_example/router/route_map.dart';

import '../../resources/Images.dart';

class MapChartChooseDemo extends StatefulWidget {
  const MapChartChooseDemo({super.key});

  @override
  State<StatefulWidget> createState() => MapChartChooseDemoState();
}

class MapChartChooseDemoState extends State<MapChartChooseDemo> {
  MapChartData data = MapChartData(
    pLine: Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke,
    pStart: Paint()..color = Colors.redAccent,
    pEnd: Paint()..color = Colors.cyan,
    pCur: Paint()..color = Colors.amberAccent,
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: KqHeadBar(
        headTitle: 'MapChart控件点选择界面',
        back: () {
          Get.back();
        },
      ),
      body: Column(
        children: [
          Stack(
            children: [
              Listener(
                child: KqImage.assets(
                  url: Images.demoWorld6,
                  fit: BoxFit.contain,
                ),
                onPointerDown: (event) {
                  if (data.end == null) {
                    data.end =
                        Point(event.localPosition.dx, event.localPosition.dy);
                  } else {
                    data.starts ??= [];
                    data.starts!.add(
                        Point(event.localPosition.dx, event.localPosition.dy));
                  }
                  setState(() {});
                },
              ),
              CustomPaint(
                painter: PointPainter(data),
              ),
            ],
          ),
          KqBottomButton(
            title: "完成选择",
            onTap: (disabled) {
              RouteMap.pushMapChartDemo(data);
            },
          ),
        ],
      ),
    );
  }
}

class PointPainter extends CustomPainter {
  final MapChartData data;

  PointPainter(this.data);

  @override
  void paint(Canvas canvas, Size size) {
    if (data.starts != null) {
      for (int i = 0; i < data.starts!.length; i++) {
        Point<double> start = data.starts![i];

        ///画起始点
        canvas.drawCircle(Offset(start.x, start.y), 5, data.pStart ?? Paint());
      }
    }

    if (data.end != null) {
      ///画终点
      canvas.drawCircle(
          Offset(data.end!.x, data.end!.y), 5, data.pEnd ?? Paint());
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}
